// 菜品上传页面JavaScript功能
class DishManager {
    constructor() {
        this.currentMerchant = null;
        this.dishes = [];
        this.currentDish = null;
        this.tags = [];
        this.galleryImages = [];
        this.init();
    }

    init() {
        this.loadCurrentMerchant();
        this.loadDishes();
        this.setupEventListeners();
        this.renderDishes();
    }

    loadCurrentMerchant() {
        const savedUser = localStorage.getItem('currentUser');
        const savedUserType = localStorage.getItem('currentUserType');
        
        if (savedUser && savedUserType === 'merchant') {
            this.currentMerchant = JSON.parse(savedUser);
        } else {
            // 演示模式：未登录商家时，自动使用第一个商家作为演示账号
            if (window.database && window.database.merchants && window.database.merchants.length > 0) {
                this.currentMerchant = window.database.merchants[0];
            } else {
                // 回退到登录页
                window.location.href = 'auth.html';
            }
        }
    }

    loadDishes() {
        this.dishes = window.database.getDishes(this.currentMerchant.id);
    }

    setupEventListeners() {
        // 标签输入
        const tagInput = document.getElementById('tagInput');
        if (tagInput) {
            tagInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    this.addTag();
                }
            });
        }

        // 图片上传
        const imageInput = document.getElementById('dishImage');
        if (imageInput) {
            imageInput.addEventListener('change', (e) => {
                this.handleImageUpload(e);
            });
        }
    }

    renderDishes() {
        const dishesGrid = document.getElementById('dishesGrid');
        const emptyState = document.getElementById('emptyState');
        
        if (this.dishes.length === 0) {
            dishesGrid.style.display = 'none';
            emptyState.style.display = 'block';
            return;
        }

        dishesGrid.style.display = 'grid';
        emptyState.style.display = 'none';
        
        dishesGrid.innerHTML = '';
        
        this.dishes.forEach(dish => {
            const dishCard = this.createDishCard(dish);
            dishesGrid.appendChild(dishCard);
        });
    }

    createDishCard(dish) {
        const card = document.createElement('div');
        card.className = 'dish-card';
        
        const statusClass = dish.status === 'available' ? 'available' : 'unavailable';
        const statusText = dish.status === 'available' ? '上架' : '下架';
        
        card.innerHTML = `
            <img src="${dish.image}" alt="${dish.name}" class="dish-image" onerror="this.src='https://via.placeholder.com/350x200/f8f9fa/666?text=暂无图片'">
            <div class="dish-content">
                <div class="dish-header">
                    <h3 class="dish-name">${dish.name}</h3>
                    <span class="dish-status ${statusClass}">${statusText}</span>
                </div>
                <p class="dish-description">${dish.description}</p>
                <div class="dish-details">
                    <div class="dish-price">
                        ¥${dish.price}
                        ${dish.originalPrice ? `<span class="dish-original-price">¥${dish.originalPrice}</span>` : ''}
                    </div>
                    <div class="dish-stats">
                        <span><i class="fas fa-shopping-cart"></i> 销量 ${dish.sales}</span>
                        <span><i class="fas fa-star"></i> ${dish.rating}</span>
                    </div>
                </div>
                <div class="dish-tags">
                    ${dish.tags ? dish.tags.map(tag => `<span class="dish-tag">${tag}</span>`).join('') : ''}
                </div>
                <div class="dish-actions">
                    <button class="btn btn-sm btn-edit" onclick="editDish(${dish.id})">
                        <i class="fas fa-edit"></i> 编辑
                    </button>
                    <button class="btn btn-sm btn-toggle" onclick="toggleDishStatus(${dish.id})">
                        <i class="fas fa-${dish.status === 'available' ? 'eye-slash' : 'eye'}"></i>
                        ${dish.status === 'available' ? '下架' : '上架'}
                    </button>
                    <button class="btn btn-sm btn-delete" onclick="deleteDish(${dish.id})">
                        <i class="fas fa-trash"></i> 删除
                    </button>
                </div>
            </div>
        `;
        
        return card;
    }

    showAddDishModal() {
        this.currentDish = null;
        this.tags = [];
        this.resetForm();
        document.getElementById('modalTitle').textContent = '添加菜品';
        document.getElementById('dishModal').classList.add('show');
    }

    editDish(dishId) {
        const dish = this.dishes.find(d => d.id === dishId);
        if (!dish) return;

        this.currentDish = dish;
        this.tags = dish.tags || [];
        this.populateForm(dish);
        document.getElementById('modalTitle').textContent = '编辑菜品';
        document.getElementById('dishModal').classList.add('show');
    }

    populateForm(dish) {
        document.getElementById('dishName').value = dish.name || '';
        document.getElementById('dishPrice').value = dish.price || '';
        document.getElementById('dishOriginalPrice').value = dish.originalPrice || '';
        document.getElementById('dishCategory').value = dish.categoryId || '';
        document.getElementById('dishDescription').value = dish.description || '';
        document.getElementById('dishStock').value = dish.stock || 0;
        document.getElementById('dishCookingTime').value = dish.cookingTime || 15;
        document.getElementById('isSpicy').checked = dish.isSpicy || false;
        document.getElementById('isVegetarian').checked = dish.isVegetarian || false;
        document.getElementById('isRecommended').checked = dish.isRecommended || false;
        document.getElementById('dishIngredients').value = dish.ingredients ? dish.ingredients.join(', ') : '';
        document.getElementById('dishAllergens').value = dish.allergens ? dish.allergens.join(', ') : '';

        // 显示现有图片
        if (dish.image) {
            this.showImagePreview(dish.image);
        }

        // 显示标签
        this.renderTags();
    }

    resetForm() {
        document.getElementById('dishForm').reset();
        this.tags = [];
        this.renderTags();
        this.hideImagePreview();
        this.galleryImages = [];
        this.renderGallery();
    }

    saveDish(event) {
        event.preventDefault();
        
        const form = event.target;
        const formData = new FormData(form);
        
        // 验证必填字段
        if (!this.validateForm(form)) {
            return;
        }

        const dishData = {
            merchantId: this.currentMerchant.id,
            name: formData.get('name'),
            price: parseFloat(formData.get('price')),
            originalPrice: parseFloat(formData.get('originalPrice')) || null,
            categoryId: parseInt(formData.get('categoryId')),
            description: formData.get('description'),
            stock: parseInt(formData.get('stock')) || 0,
            cookingTime: parseInt(formData.get('cookingTime')) || 15,
            isSpicy: formData.get('isSpicy') === 'on',
            isVegetarian: formData.get('isVegetarian') === 'on',
            isRecommended: formData.get('isRecommended') === 'on',
            ingredients: formData.get('ingredients') ? formData.get('ingredients').split(',').map(i => i.trim()) : [],
            allergens: formData.get('allergens') ? formData.get('allergens').split(',').map(a => a.trim()) : [],
            tags: this.tags,
            image: this.getCurrentImage(),
            gallery: this.galleryImages.slice(0, 5)
        };

        try {
            if (this.currentDish) {
                // 编辑现有菜品
                Object.assign(this.currentDish, dishData);
                window.database.updateDish(this.currentDish.id, dishData);
                this.showMessage('菜品更新成功！', 'success');
            } else {
                // 添加新菜品
                const newDish = window.database.addDish(dishData);
                this.dishes.push(newDish);
                this.showMessage('菜品添加成功！', 'success');
            }
            
            this.closeDishModal();
            this.renderDishes();
        } catch (error) {
            this.showMessage('保存失败，请稍后重试！', 'error');
        }
    }

    validateForm(form) {
        let isValid = true;
        const requiredFields = form.querySelectorAll('input[required], select[required], textarea[required]');
        
        requiredFields.forEach(field => {
            if (!this.validateField(field)) {
                isValid = false;
            }
        });
        
        return isValid;
    }

    validateField(field) {
        const value = field.value.trim();
        let isValid = true;
        let errorMessage = '';

        // 清除之前的错误状态
        field.closest('.form-group').classList.remove('error');
        const existingError = field.closest('.form-group').querySelector('.error-text');
        if (existingError) {
            existingError.remove();
        }

        // 必填字段验证
        if (field.hasAttribute('required') && !value) {
            isValid = false;
            errorMessage = '此字段为必填项';
        }

        // 价格验证
        if (field.name === 'price' && value) {
            const price = parseFloat(value);
            if (isNaN(price) || price < 0) {
                isValid = false;
                errorMessage = '请输入有效的价格';
            }
        }

        // 显示错误信息
        if (!isValid) {
            field.closest('.form-group').classList.add('error');
            const errorDiv = document.createElement('div');
            errorDiv.className = 'error-text';
            errorDiv.textContent = errorMessage;
            field.closest('.form-group').appendChild(errorDiv);
        }

        return isValid;
    }

    addTag() {
        const tagInput = document.getElementById('tagInput');
        const tag = tagInput.value.trim();
        
        if (tag && !this.tags.includes(tag)) {
            this.tags.push(tag);
            tagInput.value = '';
            this.renderTags();
        }
    }

    removeTag(tag) {
        this.tags = this.tags.filter(t => t !== tag);
        this.renderTags();
    }

    renderTags() {
        const container = document.getElementById('tagsContainer');
        container.innerHTML = '';
        
        this.tags.forEach(tag => {
            const tagElement = document.createElement('div');
            tagElement.className = 'tag';
            tagElement.innerHTML = `
                ${tag}
                <button type="button" class="tag-remove" onclick="removeTag('${tag}')">
                    <i class="fas fa-times"></i>
                </button>
            `;
            container.appendChild(tagElement);
        });
    }

    handleImageUpload(event) {
        const file = event.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = (e) => {
                this.showImagePreview(e.target.result);
            };
            reader.readAsDataURL(file);
        }
    }

    handleGalleryUpload(event) {
        const files = Array.from(event.target.files || []);
        if (!files.length) return;
        const remain = Math.max(0, 5 - this.galleryImages.length);
        const slice = files.slice(0, remain);
        let loaded = 0;
        slice.forEach(file => {
            const reader = new FileReader();
            reader.onload = (e) => {
                this.galleryImages.push(e.target.result);
                loaded++;
                if (loaded === slice.length) this.renderGallery();
            };
            reader.readAsDataURL(file);
        });
        // 清空input以便下次选择相同文件
        event.target.value = '';
    }

    showImagePreview(imageSrc) {
        const uploadContent = document.getElementById('uploadContent');
        const imagePreview = document.getElementById('imagePreview');
        const previewImg = document.getElementById('previewImg');
        
        uploadContent.style.display = 'none';
        imagePreview.style.display = 'block';
        previewImg.src = imageSrc;
    }

    hideImagePreview() {
        const uploadContent = document.getElementById('uploadContent');
        const imagePreview = document.getElementById('imagePreview');
        
        uploadContent.style.display = 'block';
        imagePreview.style.display = 'none';
    }

    removeImage() {
        document.getElementById('dishImage').value = '';
        this.hideImagePreview();
    }

    removeGalleryImage(index) {
        this.galleryImages.splice(index, 1);
        this.renderGallery();
    }

    renderGallery() {
        const wrap = document.getElementById('galleryPreview');
        if (!wrap) return;
        wrap.innerHTML = '';
        this.galleryImages.forEach((src, idx) => {
            const item = document.createElement('div');
            item.className = 'gallery-item';
            item.innerHTML = `
                <img src="${src}" alt="图${idx+1}">
                <button type="button" class="gallery-remove" onclick="removeGalleryImage(${idx})">×</button>
            `;
            wrap.appendChild(item);
        });
    }

    getCurrentImage() {
        const previewImg = document.getElementById('previewImg');
        return previewImg.src || 'https://via.placeholder.com/300x200/f8f9fa/666?text=暂无图片';
    }

    toggleDishStatus(dishId) {
        const dish = this.dishes.find(d => d.id === dishId);
        if (!dish) return;

        const newStatus = dish.status === 'available' ? 'unavailable' : 'available';
        const action = newStatus === 'available' ? '上架' : '下架';
        
        if (confirm(`确定要${action}这个菜品吗？`)) {
            dish.status = newStatus;
            window.database.updateDish(dishId, { status: newStatus });
            this.renderDishes();
            this.showMessage(`菜品已${action}！`, 'success');
        }
    }

    deleteDish(dishId) {
        this.dishToDelete = dishId;
        document.getElementById('deleteModal').classList.add('show');
    }

    confirmDelete() {
        if (this.dishToDelete) {
            const dish = this.dishes.find(d => d.id === this.dishToDelete);
            if (dish) {
                this.dishes = this.dishes.filter(d => d.id !== this.dishToDelete);
                window.database.deleteDish(this.dishToDelete);
                this.renderDishes();
                this.showMessage('菜品已删除！', 'success');
            }
        }
        this.closeDeleteModal();
    }

    closeDishModal() {
        document.getElementById('dishModal').classList.remove('show');
        this.resetForm();
    }

    closeDeleteModal() {
        document.getElementById('deleteModal').classList.remove('show');
        this.dishToDelete = null;
    }

    searchDishes() {
        const query = document.getElementById('searchInput').value.toLowerCase();
        this.filterDishes();
    }

    filterDishes() {
        const searchQuery = document.getElementById('searchInput').value.toLowerCase();
        const categoryFilter = document.getElementById('categoryFilter').value;
        const statusFilter = document.getElementById('statusFilter').value;
        
        let filteredDishes = this.dishes;
        
        // 按搜索关键词筛选
        if (searchQuery) {
            filteredDishes = filteredDishes.filter(dish => 
                dish.name.toLowerCase().includes(searchQuery) ||
                dish.description.toLowerCase().includes(searchQuery)
            );
        }
        
        // 按分类筛选
        if (categoryFilter) {
            filteredDishes = filteredDishes.filter(dish => dish.categoryId == categoryFilter);
        }
        
        // 按状态筛选
        if (statusFilter) {
            filteredDishes = filteredDishes.filter(dish => dish.status === statusFilter);
        }
        
        this.renderFilteredDishes(filteredDishes);
    }

    renderFilteredDishes(dishes) {
        const dishesGrid = document.getElementById('dishesGrid');
        const emptyState = document.getElementById('emptyState');
        
        if (dishes.length === 0) {
            dishesGrid.style.display = 'none';
            emptyState.style.display = 'block';
            return;
        }

        dishesGrid.style.display = 'grid';
        emptyState.style.display = 'none';
        
        dishesGrid.innerHTML = '';
        
        dishes.forEach(dish => {
            const dishCard = this.createDishCard(dish);
            dishesGrid.appendChild(dishCard);
        });
    }

    showMessage(message, type) {
        // 移除现有消息
        const existingMessage = document.querySelector('.error-message, .success-message');
        if (existingMessage) {
            existingMessage.remove();
        }

        // 创建新消息
        const messageDiv = document.createElement('div');
        messageDiv.className = type === 'error' ? 'error-message' : 'success-message';
        messageDiv.textContent = message;

        // 插入到页面顶部
        const container = document.querySelector('.dish-upload-container');
        container.insertBefore(messageDiv, container.firstChild);

        // 自动移除消息
        setTimeout(() => {
            if (messageDiv.parentNode) {
                messageDiv.remove();
            }
        }, 3000);
    }
}

// 全局函数
function showAddDishModal() {
    window.dishManager.showAddDishModal();
}

function editDish(dishId) {
    window.dishManager.editDish(dishId);
}

function deleteDish(dishId) {
    window.dishManager.deleteDish(dishId);
}

function toggleDishStatus(dishId) {
    window.dishManager.toggleDishStatus(dishId);
}

function confirmDelete() {
    window.dishManager.confirmDelete();
}

function closeDishModal() {
    window.dishManager.closeDishModal();
}

function closeDeleteModal() {
    window.dishManager.closeDeleteModal();
}

function searchDishes() {
    window.dishManager.searchDishes();
}

function filterDishes() {
    window.dishManager.filterDishes();
}

function handleImageUpload(event) {
    window.dishManager.handleImageUpload(event);
}

function removeImage() {
    window.dishManager.removeImage();
}

function handleGalleryUpload(event) {
    window.dishManager.handleGalleryUpload(event);
}

function removeGalleryImage(index) {
    window.dishManager.removeGalleryImage(index);
}

function addTag() {
    window.dishManager.addTag();
}

function removeTag(tag) {
    window.dishManager.removeTag(tag);
}

function saveDish(event) {
    window.dishManager.saveDish(event);
}

function goBack() {
    window.history.back();
}

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    window.dishManager = new DishManager();
});

